/*
* Copyright 2010 Competentum group
*
* Licensed under the GNU General Public License, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.gnu.org/licenses/gpl.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.competentum.builders
{
	import com.competentum.engines.ProjectsEngine;
	import com.competentum.windows.Scope;
	import com.competentum.lib.data.builders.AbstractDataBuilder;
	import com.competentum.lib.exceptions.NoSuchDataBuilderError;
	
	import flash.errors.IllegalOperationError;

	/**
	 * Factory for all builders. Only 1 instance of each builder in each scope can exist
	 * @author Valentine Abanosimov
	 */	
	public class DataBuildersFactory
	{
		private static var scopes:Vector.<Scope> = new Vector.<Scope>();
		private static var globalScope:Scope = new Scope(null);
		
		private static function getScopeIndex(scope:Scope):int
		{
			for (var i:int = 0; i < scopes.length; i ++ )
			{
				if (scopes[i] == scope)
				{
					return i;
				}
			}
			return -1;
		}
		
		/*public static function removeScope(scope:Scope):void
		{
			if (scopes.length > 1)
			{
				scopes.splice(getScopeIndex(scope), 1);
			}
		}*/
		
		public static function getDataBuilder(type:String, scope:Scope):AbstractDataBuilder
		{
			if (scope)
			{
				var builder:AbstractDataBuilder = scope.getBuilder(type);
				if (builder)
				{
					return builder;
				}
			}
			switch (type)
			{
				case EmployeesBuilder.TYPE:
					builder = new EmployeesBuilder(scope);
					break;
				case ProjectsBuilder.TYPE:
					builder = new ProjectsBuilder(scope);
					break;
				case BindsBuilder.TYPE:
					builder = new BindsBuilder(scope);
					break;
				case PreferencesBuilder.TYPE:
					builder = new PreferencesBuilder(scope);
					break;
				default:
					throw new NoSuchDataBuilderError();
			}
			if (builder.global)
			{
				if (globalScope.getBuilder(type))
				{
					builder = globalScope.getBuilder(type);
				}
				else
				{
					globalScope.add(builder);
				}
			}
			else
			{
				scope.add(builder);
			}
			return builder;
		}
	}
}